﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Revit;
using YJKCodeBase.WinForm;
using YJKView;

namespace GlobleSetModule
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdAssistLevel : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
			this.m_selection = cmdData.Application.ActiveUIDocument.Selection;
			RevitVersionFuncs.ClearSelection(this.m_selection);
			CmdViewType types = CmdViewType.Elevation;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			if (CmdAssistLevel._hWndRevit == null)
			{
				Process currentProcess = Process.GetCurrentProcess();
				IntPtr mainWindowHandle = currentProcess.MainWindowHandle;
				CmdAssistLevel._hWndRevit = new WindowHandle(mainWindowHandle);
			}
			DlgAssistLevel dlgAssistLevel = new DlgAssistLevel(cmdData);
			dlgAssistLevel.Show(CmdAssistLevel._hWndRevit);
			int wMsg = 7;
			CmdAssistLevel.SendMessage(CmdAssistLevel._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			Transaction transaction = null;
			transaction = new Transaction(this.m_doc);
			transaction.Start("assistlevel");
			try
			{
				bool flag;
				do
				{
					flag = this.AddLevel(dlgAssistLevel);
					cmdData.Application.ActiveUIDocument.Document.Regenerate();
				}
				while (flag);
				transaction.Commit();
			}
			catch (Exception)
			{
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				dlgAssistLevel.Close();
				return Autodesk.Revit.UI.Result.Failed;
			}
			dlgAssistLevel.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public bool AddLevel(DlgAssistLevel dlg)
		{
			try
			{
				LevelFilter levelFilter = new LevelFilter();
				Reference reference = this.m_selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, levelFilter, "请选择参考标高");
				Level level = this.m_doc.GetElement(reference) as Level;
				double val = dlg.Offset();
				FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.m_doc);
				FilteredElementCollector filteredElementCollector2 = filteredElementCollector.OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(Level));
				foreach (ElementId elementId in filteredElementCollector2.ToElementIds())
				{
					Level level2 = this.m_doc.GetElement(elementId) as Level;
					if (level2 != null && level2.Name.CompareTo(dlg.LevelName()) == 0)
					{
						MessageBox.Show("当前项目中已有同名楼层，请重新设置层名！", "盈建科提示");
						return true;
					}
				}
				Level level3 = this.m_doc.HyNewLevel(level.Elevation + AssistFunc.mmToFeet(val));
				level3.Name = dlg.LevelName();
				level3.ChangeLevelType(dlg.LevelStyle());
				FilteredElementCollector filteredElementCollector3 = new FilteredElementCollector(this.m_doc);
				filteredElementCollector3.OfClass(typeof(LinePatternElement));
				foreach (Element element in filteredElementCollector3)
				{
					LinePatternElement linePatternElement = element as LinePatternElement;
					if (linePatternElement.Name == "中心线")
					{
						ElementId id = linePatternElement.Id;
						LevelType levelType = level3.GetLevelType(this.m_doc);
						levelType.get_Parameter(BuiltInParameter.LINE_PATTERN).Set(id);
						levelType.get_Parameter(BuiltInParameter.LINE_COLOR).Set(8421504);
						break;
					}
				}
                ViewPlan viewPlan = RevitVersionFuncs.NewViewPlan(this.m_doc, level3.Name, level3, (ViewPlanType)1);
				if (viewPlan != null)
				{
					viewPlan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).Set(1);
					Parameter parameter = viewPlan.GetParameter("视图分类-父");
					if (parameter != null)
					{
						string text = "";
						if (this.GetPlanViewDirParent(ref text))
						{
							parameter.Set(text);
						}
					}
				}
			}
			catch (Exception)
			{
				return false;
			}
			return true;
		}

		private bool GetPlanViewDirParent(ref string strParent)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.m_doc);
			FilteredElementCollector filteredElementCollector2 = filteredElementCollector.OfCategory(BuiltInCategory.OST_Views).OfClass(typeof(ViewPlan));
			foreach (ElementId elementId in filteredElementCollector2.ToElementIds())
			{
				ViewPlan viewPlan = this.m_doc.GetElement(elementId) as ViewPlan;
                if (viewPlan != null && (int)viewPlan.ViewType == 1)
				{
					Parameter parameter = viewPlan.GetParameter("视图分类-父");
					if (parameter != null)
					{
						strParent = parameter.AsString();
						return true;
					}
				}
			}
			return false;
		}

		public static WindowHandle _hWndRevit;

		private Document m_doc;

		private Selection m_selection;
	}
}
